<script setup>
    import { ref, computed } from 'vue'
    import { ElMessage } from 'element-plus'

    // 保留页面跳转逻辑
    const switchPage = (pageName) => {
        window.location.href = window.location.pathname + `?page=${pageName}`
    }

    // 校园卡数据（简化版）
    const cards = ref([
        { id: '10001', balance: 150.0, status: 'active', userName: '张三' },
        { id: '10002', balance: 80.5, status: 'active', userName: '李四' },
        { id: '10003', balance: 200.0, status: 'inactive', userName: '王五' }
    ])

    // 商品数据
    const products = ref([
        { id: 1, name: '矿泉水', price: 2.5, stock: 10 },
        { id: 2, name: '可乐', price: 3.0, stock: 8 },
        { id: 3, name: '薯片', price: 5.5, stock: 5 }
    ])

    // 自动售货机状态
    const currentCard = ref(null)
    const cardInput = ref('')
    const cart = ref([])

    // 计算属性
    const totalAmount = computed(() => {
        return cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
    })

    const canCheckout = computed(() => {
        return currentCard.value && cart.value.length > 0 && currentCard.value.balance >= totalAmount.value
    })

    // 验证校园卡
    const verifyCard = () => {
        if (!cardInput.value) {
            ElMessage.error('请输入校园卡号')
            return
        }

        const card = cards.value.find(c => c.id === cardInput.value)
        if (!card) {
            ElMessage.error('校园卡不存在')
            return
        }

        if (card.status !== 'active') {
            ElMessage.error('校园卡已停用')
            return
        }

        currentCard.value = card
        ElMessage.success(`验证成功，欢迎 ${card.userName}，当前余额: ¥${card.balance.toFixed(2)}`)
    }

    // 自动售货机操作
    const addToCart = (product) => {
        if (!currentCard.value) {
            ElMessage.error('请先验证校园卡')
            return
        }

        if (product.stock <= 0) {
            ElMessage.error('商品已售罄')
            return
        }

        const existItem = cart.value.find(item => item.id === product.id)
        if (existItem) {
            existItem.quantity++
        } else {
            cart.value.push({ ...product, quantity: 1 })
        }
        product.stock--
        ElMessage.success(`${product.name} 已添加到购物车`)
    }

    const removeFromCart = (index) => {
        const item = cart.value[index]
        products.value.find(p => p.id === item.id).stock += item.quantity
        cart.value.splice(index, 1)
        ElMessage.success('已从购物车移除')
    }

    const checkout = () => {
        if (!canCheckout.value) return

        currentCard.value.balance -= totalAmount.value
        ElMessage.success(`支付成功！剩余余额：¥${currentCard.value.balance.toFixed(2)}`)
        cart.value = []
    }
</script>

<template>
    <div class="vending-container">
        <!-- 顶部导航（仅保留跳转按钮） -->
        <div class="header">
            <el-button type="primary" @click="switchPage('userManagement')" plain>
                用户管理
            </el-button>
            <el-button type="primary" @click="switchPage('campusCardManagement')" plain>
                校园卡管理
            </el-button>
        </div>

        <!-- 自动售货机主内容 -->
        <div class="vending-machine">
            <!-- 校园卡验证区域 -->
            <div class="card-verify" v-if="!currentCard">
                <el-input v-model="cardInput" placeholder="请输入校园卡号" style="width: 300px; margin-right: 10px" />
                <el-button type="primary" @click="verifyCard">验证</el-button>
            </div>

            <!-- 已验证校园卡信息 -->
            <div class="status-bar" v-else>
                <div class="card-info">
                    <span class="label">校园卡：</span>
                    {{ currentCard.id }} ({{ currentCard.userName }})
                </div>
                <div class="balance">
                    <span class="label">余额：</span>
                    ¥{{ currentCard.balance.toFixed(2) }}
                </div>
                <el-button type="text" @click="currentCard = null; cart = []">切换卡片</el-button>
            </div>

            <!-- 商品展示 -->
            <div class="product-grid">
                <div v-for="product in products" :key="product.id"
                    :class="['product-item', { 'out-of-stock': product.stock <= 0 }]" @click="addToCart(product)">
                    <div class="product-info">
                        <h3>{{ product.name }}</h3>
                        <p>¥{{ product.price.toFixed(2) }}</p>
                        <p class="stock">库存: {{ product.stock }}</p>
                    </div>
                </div>
            </div>

            <!-- 购物车 -->
            <div class="cart-section">
                <h3>购物车 ({{ cart.length }})</h3>
                <div v-if="cart.length === 0" class="empty-cart">购物车为空</div>
                <ul v-else class="cart-items">
                    <li v-for="(item, index) in cart" :key="index">
                        {{ item.name }} × {{ item.quantity }}
                        <span class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                        <el-button size="small" type="text" @click.stop="removeFromCart(index)">删除</el-button>
                    </li>
                </ul>
                <div class="cart-total" v-if="cart.length > 0">
                    总计: ¥{{ totalAmount.toFixed(2) }}
                    <div v-if="currentCard" class="balance-check">
                        {{ currentCard.balance >= totalAmount ? '余额充足' : '余额不足' }}
                    </div>
                </div>
                <el-button class="checkout-btn" type="success" :disabled="!canCheckout" @click="checkout">
                    校园卡支付
                </el-button>
            </div>
        </div>
    </div>
</template>

<style scoped>
    .vending-container {
        max-width: 1000px;
        margin: 0 auto;
        padding: 20px;
    }

    .header {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
    }

    /* 自动售货机样式 */
    .vending-machine {
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    }

    .card-verify {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        padding: 15px;
        background: #f5f7fa;
        border-radius: 8px;
    }

    .status-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 15px;
        background: #f0f2f5;
        border-radius: 8px;
        margin-bottom: 20px;
    }

    .status-bar .label {
        font-weight: bold;
        color: #666;
    }

    .product-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 15px;
        margin-bottom: 25px;
    }

    .product-item {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 15px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
    }

    .product-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .product-item.out-of-stock {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .product-info h3 {
        margin: 0 0 8px;
        font-size: 16px;
    }

    .product-info p {
        margin: 5px 0;
        color: #666;
    }

    .stock {
        color: #f56c6c;
        font-weight: bold;
    }

    .cart-section {
        border-top: 2px solid #67c23a;
        padding: 15px;
        background: #f8fafc;
        border-radius: 8px;
    }

    .cart-section h3 {
        margin-top: 0;
        color: #67c23a;
    }

    .empty-cart {
        color: #999;
        text-align: center;
        padding: 20px;
    }

    .cart-items {
        list-style: none;
        padding: 0;
        max-height: 200px;
        overflow-y: auto;
    }

    .cart-items li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px dashed #eaeaea;
    }

    .item-price {
        font-weight: bold;
        color: #f56c6c;
    }

    .cart-total {
        text-align: right;
        font-weight: bold;
        font-size: 18px;
        margin: 15px 0;
    }

    .balance-check {
        font-size: 14px;
        color: #67c23a;
    }

    .checkout-btn {
        width: 100%;
        padding: 12px;
        font-size: 16px;
    }
</style>